package edu.gzc.nio.datagram;

import java.io.IOException;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Iterator;
import java.util.Set;

/**
 * @Description: 服务端
 * @Author: guozongchao
 * @Date: 2021/1/8 10:09
 */
public class Server {
    public static void main(String[] args) throws IOException {
        DatagramChannel dgChannel = DatagramChannel.open();

        dgChannel.bind(new InetSocketAddress(9898));

        dgChannel.configureBlocking(false); //重要
        Selector selector = Selector.open();

        dgChannel.register(selector, SelectionKey.OP_READ);

        //监听注册的通道是否有就绪事件
        while (selector.select() > 0) {
            //获取注册的通道与selector的关系对象集合迭代器
            //SelectionKey描述了channel和selector注册关系
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();

            //遍历
            while (iterator.hasNext()) {
                //获取单个SelectionKey
                SelectionKey sk = iterator.next();

                if (sk.isReadable()) {  //监听通道是否可读就绪
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    dgChannel.receive(buffer);
                    String remoteAddress = dgChannel.getRemoteAddress().toString();
                    buffer.flip();
                    System.out.println(remoteAddress+":"+new String(buffer.array()));
                    buffer.clear();
                }
                iterator.remove();
            }
        }
        dgChannel.close();
    }
}
